/**
 * 自定义公共函数
 */
var myfn = {};
const db = uniCloud.database();
/**
 * 测试函数test1
 * vk.myfn.test1();
 */
myfn.test1 = function(obj = {}) {
	console.log("执行了自定义公共函数test1");
	obj.hedian = "hediankeji";
	return obj.hedian;
};

/**
 * 校验是否登录的函数
 * vk.myfn.checkLogin();
 */
myfn.checkLogin = async function(obj = {}) {
	console.log("执行了自定义公共函数checkLogin");
	let tt_openid = uni.vk.vuex.get('$user.userInfo.tt_openid');
	if (tt_openid) {
		console.log("存在用户信息");
		let openid_md5 = await openid_to_md5(tt_openid)
		//通过openid去数据库里取最新数据
		uni.vk.userCenter.login({
			data: {
				username: openid_md5,
				password: "123456",
			},

			success: (data) => {
				load_recharge()
				loadUserData()
				uni.vk.vuex.set('$user.userInfo', data.userInfo)
				myfn.updataTime()
			}
		});
		return;
	} else {
		console.log("不存在用户信息，自动登录注册");
		await uni.vk.myfn.ttlogin()
	}
	return obj;
};

let timer = null

// 定时计算会员是否到期
myfn.updataTime = async function() {
	vk.vuex.set('timeStr', calculateTimeDifference(vk.vuex.get(
		'$user.userInfo.plus_expire_time')))
	clearInterval(timer);
	if (uni.vk.vuex.get('$user.userInfo.plus_type') == 1) {
		timer = setInterval(() => {
			vk.vuex.set('timeStr', calculateTimeDifference(vk.vuex.get(
				'$user.userInfo.plus_expire_time')))
		}, 1000);
	}


};
// 格式化时间
function calculateTimeDifference(targetTimeMs) {
	const currentTime = new Date();
	const targetTime = new Date(targetTimeMs);

	const timeDifference = targetTime - currentTime;
	// console.log("7777777777777", timeDifference);
	const hours = Math.floor(timeDifference / (1000 * 60 * 60));
	const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
	const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

	const positiveHours = Math.max(hours, 0);
	const positiveMinutes = Math.max(minutes, 0);
	const positiveSeconds = Math.max(seconds, 0);

	if (timeDifference < 0) {
		clearInterval(timer);
		setTimeout(() => {
			vk.callFunction({
				url: 'client/pages/kh/index_userdata',
				data: {
					todatStart: vk.vuex.get('$app.time.todayStart'),
				},
				success: (res) => {
					console.log("看看到期返回", res);
					uni.vk.myfn.ttlogin().then(() => {
						console.log("ok登陆了");
					});
				}
			});

		}, 1000)
	}
	if (hours === 0) {
		return `${positiveMinutes}分钟${positiveSeconds}秒`;
	} else {
		if (!positiveHours && !positiveMinutes) return "登陆中"
		return `${positiveHours}小时${positiveMinutes}分钟`;
	}

};
/**
 * 字节跳动小程序登录函数ttlogin
 * vk.myfn.ttlogin();
 */
myfn.ttlogin = async function(obj = {}) {
	// 自动注册和自动登录
	const loginResult = await new Promise((resolve, reject) => {
		tt.login({
			success(res) {
				console.log("code=", res);
				resolve(res);
			},
			fail(err) {
				reject(err);
			}
		});
	});

	const callFunctionResult = await new Promise((resolve, reject) => {
		uni.vk.callFunction({
			url: 'admin/pages/pub/ttlogin',
			data: {
				code: loginResult.code,
				appid: uni.vk.vuex.get('$app.appid'),
			},
			success: (data) => {

				resolve(data);
			},
			fail(err) {
				reject(err);
			}
		});
	});

	await ttloginByopenid(callFunctionResult.openid);

};

//单独抽离出来的函数
async function ttloginByopenid(openid) {
	let openid_md5 = await openid_to_md5(openid)
	uni.vk.callFunction({
		url: 'client/pages/pub/checkuser',
		// title: '请求中...',
		data: {
			openid_md5: openid_md5
		},
		success: (data) => {
			console.log("data=", data);
			let existNum = data.user.data.length || 0;
			console.log("已存在用户数：", existNum);
			//已存在则直接登录
			if (existNum > 0) {
				uni.vk.userCenter.login({
					data: {
						username: openid_md5,
						password: "123456",
					},
					success: (data) => {
						load_recharge()
						loadUserData()
					}
				});
			}
			//不存在用户则进行注册
			if (existNum == 0) {
				console.log("openid_md5=", openid_md5);
				var nowtime = new Date().getTime();
				uni.vk.userCenter.register({
					data: {
						username: openid_md5,
						password: "123456",
						tt_openid: openid,
						platform: "tt",
						balance: 0,
						plus_type: 0,
						register_date: nowtime,
						plus_expire_time: nowtime,
						status: 0,
						invite_code: uni.getStorageSync('invite_code') || 0,
						reward_times: 0,
						had_youhui: false,
						finish: {
							libao: false,
							jiesuo: false,
							shoujihao: false,
							dingyue: false,
							xinren: false,
						},
						reback: 0,
						appid: uni.vk.vuex.get('$app.appid'),
						appname: uni.vk.vuex.get('$app.appname'),
						needPermission: false,
						ad_id: uni.getStorageSync('adid') || 0,
						tg_pt: uni.getStorageSync('tg_pt') || 0,
						creativeid: uni.getStorageSync('creativeid') || 0,
						creativetype: uni.getStorageSync('creativetype') || 0,
						clickid: uni.getStorageSync('clickid') || 0,
						middleman_id: uni.getStorageSync('middleman_id') || 0,
						tfid: uni.getStorageSync('tfid') || 0,
						promotion_id: uni.getStorageSync('promotion_id') || 0,
						clue_token: uni.getStorageSync('clue_token') || 0,
						req_id: uni.getStorageSync('req_id') || 0,
						advertiser_id: uni.getStorageSync('advertiser_id') || 0,
						projectid: uni.getStorageSync('projectid') || 0,
						is_paid: false, //记录用户是否已支付
						last_login_date: new Date().getTime(),

					},
					success: (data) => {
						load_recharge()
						loadUserData()
						// 注册成功后的逻辑
						console.log("data=", data);
					}
				});
			}
		}
	});
}

async function openid_to_md5(openid) {
	//自定义MD5加密函数
	const crypto = require('crypto');
	const md5 = crypto.createHash('md5');
	let openid_LowerCase = openid.toLowerCase();
	let openid_md5 = md5.update(openid_LowerCase).digest('hex');
	return openid_md5;
}

async function load_recharge() {
	vk.callFunction({
		url: 'client/pay/kh/get_rechargelist',
		// title: '请求中...',
		data: {
			appid: vk.vuex.get('$app.appid')
		},
		success: (data) => {
			vk.vuex.set('$app.rechargelist', data.recharge)
		}
	});
}

async function loadUserData() {
	vk.callFunction({
		url: 'client/pages/kh/index_userdata',
		data: {
			todatStart: vk.vuex.get('$app.time.todayStart'),
		},
		success: (res) => {}
	});
}

export default myfn;